var app = getApp();
var paymeny = 0;
// pages/gettingWater/gettingWater.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        big: '../../images/8_l.png', //水量8L
        big_red: '../../images/8_r.png',
        content: '../../images/5_l.png', //水量5L
        content_red: '../../images/5_r.png',
        samll: '../../images/1_l.png', //水量1L
        samll_red: '../../images/1_r.png',
        waterType: '',
        waterType_k: 0,
        watwerone: '',
        watwertwo: '',
        watwerthree: '',
        popupshow: false,
        selectcoupon: false,
        equipment_sn: '',
        w_conf: [],
        conf_source: '',
        userinfo: [],
        cards: [],
        balance: "0.00",
        card_sn: "xxxx",
        card_id: 0,
        money: 0,
        flag: true,
        pay_type: 2, //支付方式 2水卡 3微信支付 1积分支付
        integral: 0,
        chooseNum: 0,
        have: '',
        rate: '', //兑换比例
        couponList: [],
        Select_coupon: '选择优惠券',
        Select_coupon_id: '',
        cp_index: 0, //优惠券index
        cose_idx: -1,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var sn;
        sn = options.equipment_sn ? options.equipment_sn : '';

        if (options.q != undefined) {

            var scan_url = decodeURIComponent(options.q); //字符分割console.log(scan_url); //打印出url//分割网址，提取出参数
            var surls = scan_url.split("equipment_sn=");
            var eid = surls[1];
            sn = eid ? eid : '';
        }
        var have = options.have ? options.have : ''; //判断是否需要返回按钮
        this.setData({
            equipment_sn: sn,
            have: have
        });
        if (!this.data.equipment_sn || this.data.equipment_sn == '') {
            app.showModal('设备信息错误');
            return false;
        }
        this.getWaterConf();

    },

    getWaterConf() {
        var that = this;
        app.ajax({
            url: "User/Equipment/getWaterConf",
            data: {
                "equipment_sn": that.data.equipment_sn
            },
            success: function(res) {
                var arr = [];
                var newobj = res.data.data.conf;
                for (var item in newobj) {
                    arr.push(newobj[item]);
                }
                that.setData({
                    conf_source: res.data.data.source,
                    w_conf: res.data.data.conf,
                    waterType: arr[0].rise,

                    watwerone: res.data.data.conf.one.rise,
                    watwertwo: res.data.data.conf.two.rise,
                    watwerthree: res.data.data.conf.three.rise,
                })

            }
        });
    },
    //返回首页
    backHome() {
        wx.redirectTo({
            url: '../home/home',
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        wx.setStorageSync('is_first', true);
        this.getUser();
        this.setData({
            flag: true
        })
        var isBack = wx.getStorageSync('isBack') || false;
        console.log('isBack', isBack);
        if (isBack) {
            this.selectcoupon();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        wx.setStorageSync('isBack', false);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },
    //选择打水量
    chooseType: function(e) {
        var that = this;
        this.setData({
            waterType: e.currentTarget.dataset.typev,
            waterType_k: e.currentTarget.dataset.typek
        })
        var cp_List = that.data.couponList;
        var c_idx = that.data.cp_index;
        var cose_idx = that.data.cose_idx;
        var getmony = that.data.money;
        var s_meny = 0;
        if (cp_List != '' && c_idx != -1) {
            s_meny = cp_List[c_idx].coupon_condition_val.reduce;
        }
        //当前点击的值
        var mone_ys = e.currentTarget.dataset.money;
        //赋值到全局
        paymeny = e.currentTarget.dataset.money;
        var rate = that.data.rate;
        var cutmoney = 0;
        if (cp_List != '' && c_idx != -1) {
            cutmoney = cp_List[c_idx].coupon_condition_val.full;
        }
        console.log('满多少?金钱', cutmoney, '当前的值', mone_ys);
        //清除优惠券选择
        if (cutmoney > mone_ys) {
            that.setData({
                Select_coupon_id: '',
                Select_coupon: '请选择优惠券',
                couponList: [],
            });
            s_meny = 0;
        }
        // pay_type  rate
        if (cose_idx == -1) {
            if (that.data.pay_type == 1) {
                that.setData({
                    money: (mone_ys / rate),
                });
            } else {
                that.setData({
                    money: mone_ys,
                });
            }
        } else {
            if (that.data.pay_type == 1) {
                that.setData({
                    money: (mone_ys / rate),
                });
            } else {
                that.setData({
                    money: mone_ys - s_meny,
                });
            }
        }


    },
    // 单选支付方式按钮
    radioChange: function(e) {
        var that = this;
        var money = that.data.money;
        var rate = that.data.rate;
        var cp_List = that.data.couponList;
        var c_idx = that.data.cp_index;
        var s_meny = 0;
        if (cp_List != '' && c_idx != -1) {
            s_meny = cp_List[c_idx].coupon_condition_val.reduce;
        }
        // console.log("这是我要的嘿", e.detail.value)
        if (e.detail.value != 1) {
            that.setData({
                money: paymeny - s_meny,
            })
        } else {
            that.setData({
                money: paymeny / rate,
                Select_coupon: '请选择优惠券',
                Select_coupon_id: '',
                couponList: [],
            })
            cp_List = '';
        }
        if (cp_List != '') {
            that.setData({
                Select_coupon_id: cp_List[c_idx].ccode_id,
                Select_coupon: '省' + cp_List[c_idx].coupon_condition_val.reduce + '元 : ' + cp_List[c_idx].coupon_condition_val.full + '元满额减券'
            })
        }
        //积分或者是微信支付
        that.setData({
            pay_type: e.detail.value
        });

        //水卡支付 是否为空
        if (e.detail.value == '2') {
            if (that.data.cards.length <= 0) {
                wx.showModal({
                    title: '暂时没有水卡',
                    content: '是否申请?',
                    confirmColor: '#FF6565',
                    success: function(res) {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '../applyElectronicCard/applyElectronicCard',
                            })
                        } else if (res.cancel) {

                        }
                    }
                })
                return false;
            }
            that.setData({
                popupshow: true
            })
        }
    },
    chooseCardWay() {
        var that = this;
        if (that.data.cards.length <= 0) {
            wx.showModal({
                title: '暂时没有水卡',
                content: '是否申请? (水卡支付优惠更多)',
                confirmColor: '#FF6565',
                success: function(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../applyElectronicCard/applyElectronicCard',
                        })
                    } else if (res.cancel) {

                    }
                }
            })
            return false;
        }
        that.setData({
            popupshow: true
        })
    },
    //选择水卡
    radioChooseCrad: function(e) {
        var that = this;
        var card = that.data.cards;
        card.forEach(function(v, k) {
            if (v.water_id == e.detail.value) {
                that.setData({
                    balance: v.balance,
                    card_sn: v.card.substr(-4),
                })
            }
        })
        that.setData({
            card_id: e.detail.value,
        })
    },
    //取消关闭弹窗
    cancelBtn: function() {
        this.setData({
            popupshow: false
        })
    },
    //确认选择水卡
    affirmBtn: function(e) {
        this.setData({
            popupshow: false
        })
    },
    //获取用户信息
    getUser() {
        var that = this;
        app.ajax({
            url: "User/User/getUser",
            data: {},
            success: function(res) {
                if (res.data.code == 1000) {
                    that.setData({
                        integral: res.data.data.integral,
                        userinfo: res.data.data,
                        rate: res.data.data.rate
                    });
                    that.getCards();
                } else {
                    wx.setStorageSync('token', '');
                    app.getToken();
                    // app.showModal('获取用户信息失败');
                }
            }
        })
    },
    getCards() {
        var that = this;
        app.ajax({
            url: "User/User/getWaterCard",
            data: {},
            success: function(res) {
                if (res.data.code == 1000) {
                    var getData = res.data.data;
                    if (getData.length > 1) {
                        getData.sort(function(a, b) {
                            return b.balance - a.balance;
                        });
                    }
                    that.setData({
                        cards: getData,
                    });
                    if (getData.length > 0) {
                        that.setData({
                            balance: getData[0].balance,
                            card_sn: getData[0].card.substr(-4),
                            card_id: getData[0].water_id
                        });
                    }
                }
            }
        })
    },
    selectcoupon: function(e) {
        var that = this;
        if (that.data.pay_type == 1) {
            app.showToast('积分支付不能使用优惠券');
            return false;
        }
        // if (!that.data.waterType_k || that.data.money==0){
        //   app.showToast('请先选择打水量'); return false;
        // }
        var cp_idx = that.data.cp_index;
        app.ajax({
            url: 'User/Coupon/selectCoupon',
            data: {
                money: paymeny
            },
            success: function(res) {
                if (res.data.code == 1000) {
                    that.setData({
                        couponList: res.data.data,
                        Select_coupon_id: res.data.data[cp_idx].ccode_id,
                        Select_coupon: '省' + res.data.data[cp_idx].coupon_condition_val.reduce + '元 : ' + res.data.data[cp_idx].coupon_condition_val.full + '元满额减券',
                    })
                }
                that.setData({
                    selectcoupon: true
                })
            }
        });
    },
    //选择优惠券
    radio_Change2(e) {
        var that = this;
        var pay_stype = that.data.pay_type;
        if (pay_stype == 1) {
            app.showToast('积分支付不能使用优惠券');
            return false;
        }
        if (e.detail.value == -1) {
            that.setData({
                cose_idx: e.detail.value,
                Select_coupon_id: '',
                Select_coupon: '不使用优惠券'
            });
            // console.log('这个结果是', e.detail.value, pay_stype, paymeny);
            // if (pay_stype==1){
            //   that.setData({
            //     money: paymeny/rate,
            //   })
            // }else{
            //   that.setData({
            //     money: paymeny,
            //   })
            //   console.log('这个结果是', that.data.money);
            // }

        } else {
            that.setData({
                cose_idx: e.detail.value,
                cp_index: e.detail.value,
                Select_coupon_id: that.data.couponList[e.detail.value].ccode_id,
                Select_coupon: '省' + that.data.couponList[e.detail.value].coupon_condition_val.reduce + '元 : ' + that.data.couponList[e.detail.value].coupon_condition_val.full + '元满额减券',
            });
        }
    },
    // 关闭选择优惠券弹窗
    closeSelectPop() {
        var that = this;
        var cp_List = that.data.couponList;
        var c_idx = that.data.cp_index;
        var cose_idx = that.data.cose_idx;
        var getmony = that.data.money;
        var s_meny = 0;
        var rate = that.data.rate;
        if (cp_List != '' && c_idx != -1) {
            s_meny = cp_List[c_idx].coupon_condition_val.reduce;
        }
        var pay_stype = that.data.pay_type;
        console.log('这个结果是', c_idx, pay_stype, paymeny);
        if (cose_idx == -1) {
            that.setData({
                money: paymeny
            })
        } else {
            that.setData({
                money: paymeny - s_meny
            })
        }
        that.setData({
            selectcoupon: false
        })
    },
    //添加订单
    addOrder() {
        var that = this;
        if (!that.data.equipment_sn) {
            app.showToast('设备信息错误');
            return false;
        }

        if (!that.data.waterType_k) {
            app.showToast('请选择打水量');
            return false;
        }

        if (!that.data.pay_type) {
            app.showToast('请选择支付方式');
            return false;
        }
        // if (that.data.balance == 0 && that.data.pay_type!=1){
        //   app.showToast('余额不足,请换卡支付'); return false;
        // }
        if (that.data.pay_type == 2 && that.data.card_id == '') {
            if (that.data.cards.length <= 0) {
                wx.showModal({
                    title: '暂时没有水卡',
                    content: '是否申请?',
                    confirmColor: '#FF6565',
                    success: function(res) {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '../applyElectronicCard/applyElectronicCard',
                            })
                        } else if (res.cancel) {

                        }
                    }
                })
                return false;
            }
            app.showToast('请选择水卡');
            return false;
        }
        if (that.data.pay_type == 1 && that.data.Select_coupon_id != '') {
            that.setData({
                Select_coupon_id: '',
                Select_coupon: '请选择优惠券',
            });
            app.showToast('积分支付不能使用优惠券');
            return false;
        }

        if (!that.data.flag) {
            return false;
        }
        that.setData({
            flag: false
        })

        app.ajax({
            url: "User/Order/order",
            load: true,
            msg: '订单生成中...',
            data: {
                water_type: that.data.waterType_k,
                equipment_number: that.data.equipment_sn,
                pay_type: that.data.pay_type,
                card_id: that.data.card_id,
                conf_source: that.data.conf_source,
                coupon_id: that.data.Select_coupon_id,
            },
            success: function(res) {
                if (res.data.code == 1000) {
                    var obj = res.data.data.order;
                    if (that.data.pay_type == 3 && res.data.data.is_wxpay == 1) {
                        //调起微信支付
                        wx.requestPayment({
                            timeStamp: obj.timeStamp,
                            nonceStr: obj.nonceStr,
                            package: obj.package,
                            signType: obj.signType,
                            paySign: obj.paySign,
                            success: function(res) {
                                that.pay_success();
                            },
                            fail: function(e) {
                                that.setData({
                                    flag: true
                                })
                                app.showToast('取消支付');
                            }
                        })
                    } else {
                        that.pay_success();
                    }
                } else {

                    app.showToast(res.data.message);
                    that.setData({
                        flag: true
                    })
                }

            }
        })
    },
    //支付成功跳转
    pay_success() {
        var that = this;
        app.showToast('支付成功', 'success');
        setTimeout(function() {
            wx.navigateTo({
                url: '../myOrderList/myOrderList?have=' + that.data.have
            })
        });
    },
    // 跳转领券中心
    goCoupon() {
        var that = this;
        wx.navigateTo({
            url: '../vouchercenter/vouchercenter?type=pay',
        })
    }
})